const { userdlzc } = require('../modules/pjw-user');
const jwt = require('jsonwebtoken');
const { TOKEN_SECRET } = require('../utils/const');
async function zhuce(req, res, next) {//注册
    const data = req.body;
    const propertyName = await userdlzc.find({ propertyName: data.propertyName });
    if (propertyName.length > 0) {
        res.send({
            message: '账号存在，注册失败',
            code: 500
        });
        return;
    }
    const result = await userdlzc.create(data);
    if (result) {
        res.send({
            message: '注册成功',
            code: 200
        });
    }
}
async function denglu(req, res, next) {//登录
    const data = req.body;
    const result = await userdlzc.find(data);
    const token = jwt.sign(//生成 token
        { user: result[0] }, //  用户信息
        TOKEN_SECRET,  // 密钥，任意字符串
        { expiresIn: '1h' } // 设置有效期
    )
    if (result.length > 0) {
        res.send({
            message: '登录成功',
            code: 200,
            token: 'Bearer ' + token
        });
    } else {
        res.send({
            message: '登录失败',
            code: 500
        });
    }
}
async function changePass(req, res, next) {//修改密码
    const data = req.body;
    console.log('修改密码', data);
    const result = await userdlzc.updateOne(data);
    res.send({
        message: '修改密码成功',
        code: 200,
    })
}
function getUserInfo(req, res) {
    const token = req.get('Authorization').split(' ')[1];  // 获取请求头中的 token
    const { user } = jwt.verify(token, TOKEN_SECRET);// 解码 token
    // console.log('获取用户信息', user);
    res.send({
        message: '用户信息获取成功',
        code: 200,
        data: user
    })
}
module.exports = {
    zhuce, denglu, getUserInfo, changePass,
}